
# Setup -------------------------------------------------------------------
rm(list = ls())
library(haven)


# Function definition -----------------------------------------------------

# Function for running individual bivariate regressions and extracting the coefficients:

indiv.reg.int <- function(formula, data, id, id.var = "ID") {
    if (id %% 10000 == 0) {
      print(paste0("Regression: ", id, "/", max(id.var), "\n"))
    }
    fit <- lm(formula, data = data[id.var == id,])
    c(id, coef(fit), sqrt(diag(vcov(fit))))
}

# Wrapper function:
indiv.reg <- function(path_in, path_out) {
  
  # Load data:
  data <- read_dta(file = path_in)
  
  # Calculate regressions:
  results <- t(sapply(X = unique(data$key), 
                      FUN = indiv.reg.int, 
                      formula = log(p_emplAft6M_0M_In) ~ ModelMonth, 
                      data = data, 
                      id.var = data$key))
  
  # Fix column names:
  colnames(results) <- c("key", "beta_0", "beta_1", "beta_0_se", "beta_1_se")
  
  # Save to csv:
  write.csv(results, file = path_out)
}


# Execution ---------------------------------------------------------------

years <- c("2006")

for (y in years) {
  
  print(paste0("Estimating ", y, " model."))
  
  # Set paths:
  main <- "placeholder_main"
  path_in <- paste0(main, "/Data/119_1_DataForR_DurationDependenceBetas_Full_", y, ".dta")
  path_out <- paste0(main, "/Data/119_2_DurationDependenceBetas_Full_", y, ".csv")
  
  # Run regressions:
  indiv.reg(path_in, path_out)
}
